import {
  queryAllPermission,
  getDetail,
  addRole,
  editRole,
  getResource,
  getAppList
} from './roleAdminDetailServ.js'
import { parse } from 'qs'
import { message } from 'antd'
import moment from 'moment'
import { isEmpty, isArray, cloneDeep, merge, get, set, concat, pick } from 'lodash'
import { hashHistory } from 'dva/router'
import AppBus from 'utils/bus'

// import menu from 'config/menu'     //菜单
// import subElements from 'config/subElements'

//   //递归遍历树节点,分拣叶子节点，制造半选状态
function filterKeys (list) {
  list = cloneDeep(list)
  if (!list) {
    return {
      checkedKeys: [],
      halfCheckedKeys: []
    }
  }
  let checkedKeys = []
  let halfCheckedKeys = []
  const loop = (list = [],) => list.map((item, index) => {
    if (item.child && item.child.length) {
      loop(item.child, index)
      halfCheckedKeys.push(item.permissionMenuId)
    } else {
      checkedKeys.push(item.permissionMenuId)
    }
  })
  loop(list, 0)
  console.log('filterKeys', checkedKeys)
  return {
    checkedKeys: checkedKeys,
    halfCheckedKeys: halfCheckedKeys
  }
  
}

const defultState = {
  loading: false,
  btnLoading: false,
  actionType: '',//edit编辑，detail详情，add新增
  detailData: {}, //详情数据
  menu: [], //菜单
  isLeaf: false, //菜单
  curSubElements: [], //当前展示的按钮列表
  treeInfo: {//tree数据
    halfCheckedKeys: [],
    expandedKeys: [],
    autoExpandParent: true,
    checkedKeys: [],   //勾选复选框
    selectedKeys: [],  //节点获得焦点
  },
}

const tmpModule = {
  state: cloneDeep(defultState),
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({pathname, query}) => {
        if ('' + tmpModule.pathname === '' + pathname) {
          //每次进来页面更新数据 重置state
          dispatch({type: 'updateStore', payload: {...cloneDeep(defultState),...query}})
          // 获取资源树
          dispatch({type: 'queryAllPermission', payload: {}})
          
          if (query.actionType == 'edit'||query.actionType == 'check') {
            // 获取详情
            dispatch({type: 'getDetail', payload: {...query}})
          }
        }
      })
    },
  },
  
  effects: {
    //查询操作
    * queryAllPermission ({payload}, {put, call, select}) {
      try {
        const {success, rows = []} = yield call(queryAllPermission, {...payload, pageSize: 10000})
        if (success) {
          // let {respDtoList, butonIdList} = data
          // rows.map((item, index) => {
          //   item.key = item.permissionMenuId
          // })
          // let list=[{
          //   "icon": "icon-shezhi",
          //   "name": "资源目录",
          //   "ord": 0,
          //   // "parentMenuId": "201",
          //   "permissionMenuId": "0" ,
          //   "child": rows ,
          // }]
          let list =rows
          yield put({type: 'updateStore', payload: {menu: list || [],...payload}})
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 获取详情
    * getDetail ({payload}, {put, call, select}) {
      let {detailData, type, data, treeInfo} = yield select(state => state[tmpModule.namespace])
      // yield put({ type: 'updateStore', payload: { ...defultState } })
      try {
        let {data, success} = yield call(getDetail, parse({permissionRoleId: payload.id}))
        if (success) {
          detailData = data
          let {permissionMenuId = [], permissionMenuList = []} = data
          // treeInfo.checkedKeys=permissionMenuId
          let nodeObj= filterKeys(permissionMenuList)
          console.log('filterKeys',nodeObj)
          treeInfo.checkedKeys = nodeObj.checkedKeys
          treeInfo.halfCheckedKeys = nodeObj.halfCheckedKeys
          
        }
        yield put({type: 'updateStore', payload: {...payload, detailData}})
      } catch (e) {
        console.error(e)
      }
    },
    
    * save ({payload}, {put, call, select}) {
      let {detailData, actionType, treeInfo} = yield select(state => state[tmpModule.namespace])
      let {checkedKeys = [],halfCheckedKeys=[]} = treeInfo || {}
    
      try {
        let param = {
          permissionRoleId: detailData.permissionRoleId || undefined,//新增时，不用传角色id
          name: String(detailData.name).trim(),
          remark: detailData.remark,
          permissionMenuId: checkedKeys.concat(halfCheckedKeys),
        }
        yield put({ type: 'updateStore', payload: { btnLoading: true } });
        let {data, resultCode} = yield call(actionType == 'add' ? addRole : editRole, param)
        yield put({ type: 'updateStore', payload: { btnLoading: false } });
        message.success(`${actionType == 'add' ? '新增' : '修改'}成功`)
        console.log("0xxxxxx");
        let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
        AppBus.emit('closeTab', {
          key: urlArray[1],
          cbf: () => {
            hashHistory.push('/home/roleAdminList')
          }
        })
      } catch (error) {
        console.error(error)
      }
    },
    * selectedKeysChange ({payload}, {put, select}) {
      let {subElements, treeInfo, curSubElements} = yield select(state => state[tmpModule.namespace])
      let {isLeaf, leafId} = treeInfo
      let {selectedRowKeys = []} = payload
      curSubElements = get(subElements, `${leafId}`, {})
      curSubElements.selectedRowKeys = selectedRowKeys
      yield put({type: 'updateStore', payload: {subElements, curSubElements}})
    },
  },
  reducers: {
    updateStore (preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
